import { useStore } from '@/hooks';
import * as api_account from '@/services/account';
import { Button, Form, Input, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useState } from 'react';
import { useHistory } from 'react-router';
import styles from './LoginBlock.module.scss';
import { trans } from '../../../../services/errmsg.js';
import { useInterval } from './utils';
import setLogin from '../../../../assets/setlogin.png';

const { Item } = Form;
const DEFAULT_DATA = {
  mobile: '',
  autoLogin: true,
  phone: '',
  code: '',
};

const layout = {
  height: 45,
};
const LoginBlock = (
  props = {
    dataSource: DEFAULT_DATA,
  },
) => {
  const { loginStore } = useStore();
  const { dataSource = DEFAULT_DATA } = props;
  const [postData, setValue] = useState(dataSource);
  const [isRunning, checkRunning] = useState(false);
  const [second, setSecond] = useState(59);
  const [loading, setLoading] = useState(false);
  const history = useHistory();
  useInterval(
    () => {
      setSecond(second - 1);

      if (second <= 0) {
        checkRunning(false);
        setSecond(59);
      }
    },
    isRunning ? 1000 : null,
  );

  const formChange = (values) => {
    setValue(values);
  };

  const sendCode = async (values, errors) => {
    if (errors) {
      return;
    }
    const { mobile } = values;
    try {
      await api_account.getPhoneCode({
        mobile, type: 0, tenantId: global.TENANT,
      });
      checkRunning(true);
    } catch (error) {
      console.log('错误', error);
    }
  };

  const handleSubmit = (values, errors) => {
    if (errors) {
      console.log('errors', errors);
      return;
    }
    setLoading(true);
    const { mobile, vcode } = values;
    loginStore
      .authSms({
        ...values,
        mobile,
        vcode,
        scope: global.SCOPE,
        tenantId: global.TENANT,
      })
      .then((_) => {
        Message.success(t`登录成功!`);
        setLoading(false);
        window.location.reload();
      })
      .catch((err) => {
        setLoading(false);
        let errTip = '';
        const { source } = err;
        console.log(t`登录失败`, source?.message || source || err);
        errTip = trans(source);
        Message.warning(errTip);
      });
  };

  const phoneForm = (
    <>
      <Item format="tel" required requiredMessage="必填" asterisk={false} style={layout}>
        <Input
          name="mobile"
          innerBefore={
            <span className={styles.innerBeforeInput}>
              +86
              <span className={styles.line} />
            </span>
          }
          //   maxLength={20}
          placeholder={t`手机号`}
        />
      </Item>
      <Item
        required
        requiredMessage="必填"
        // style={{
        //   marginBottom: 0,

        // }}
        // eslint-disable-next-line react/jsx-props-no-multi-spaces
        style={layout}
      >
        <Input
          name="vcode"
          innerAfter={
            <span className={styles.innerAfterInput}>
              <span className={styles.line} />
              <Form.Submit
                text
                type="primary"
                style={{
                  width: 64,
                }}
                disabled={!!isRunning}
                validate={['phone']}
                onClick={sendCode}
                className={styles.sendCode}
              >
                {isRunning ? `${second}秒后再试` : t`获取验证码`}
              </Form.Submit>
            </span>
          }
          //   maxLength={20}
          placeholder={t`验证码`}
        />
      </Item>
    </>
  );

  return (
    <div>
      <div className={styles.innerBlock}>
        <div
          style={{ color: '#126be9', fontWeight: 'bold', fontSize: 24, textAlign: 'center', margin: 20 }}
        >{t`调度员登录`}
        </div>
        <Form value={postData} onChange={formChange} size="large">
          {phoneForm}

          <div className={styles.infoLine}>
            <Item
              style={{
                marginBottom: 10,
              }}
            />
          </div>

          <div style={{ marginBottom: 10 }}>
            <img style={{ width: '18px', marginRight: '3px', marginBottom: -5 }} src={setLogin} alt="" />
            <span>管理员请<Button text type="primary" style={{ marginBottom: 2 }} onClick={() => history.push('/user/login')}>点击这里</Button>，用账户密码登录</span>
          </div>

          <Item
            style={{
              marginBottom: 10,
            }}
          >
            <Form.Submit
              loading={loading}
              type="primary"
              htmlType="submit"
              onClick={handleSubmit}
              className={styles.submitBtn}
              validate
            >
              {t`登录`}
            </Form.Submit>
          </Item>
        </Form>
      </div>
    </div>
  );
};

export default LoginBlock;
